<?php
// 直接连接数据库
$host = '127.0.0.1';
$dbname = 'dyorder';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // 删除已存在的orders表
    $pdo->exec('DROP TABLE IF EXISTS orders');
    echo "已删除旧的orders表\n";
    
    // 创建新的orders表
    $sql = "CREATE TABLE orders (
        id INT AUTO_INCREMENT PRIMARY KEY,
        order_no VARCHAR(100) NOT NULL COMMENT '订单号',
        platform VARCHAR(50) NOT NULL COMMENT '平台',
        order_date DATE NOT NULL COMMENT '订单日期',
        customer_name VARCHAR(100) COMMENT '客户姓名',
        product_name VARCHAR(200) COMMENT '商品名称',
        quantity INT DEFAULT 1 COMMENT '数量',
        unit_price DECIMAL(10,2) DEFAULT 0.00 COMMENT '单价',
        total_amount DECIMAL(10,2) DEFAULT 0.00 COMMENT '总金额',
        cost_price DECIMAL(10,2) DEFAULT 0.00 COMMENT '成本价',
        profit DECIMAL(10,2) DEFAULT 0.00 COMMENT '利润',
        status VARCHAR(50) DEFAULT 'pending' COMMENT '状态',
        source_data TEXT COMMENT '原始数据',
        sync_date DATETIME NULL COMMENT '同步日期',
        created_at DATETIME NULL COMMENT '创建时间',
        updated_at DATETIME NULL COMMENT '更新时间',
        INDEX idx_order_no (order_no),
        INDEX idx_platform (platform),
        INDEX idx_order_date (order_date),
        INDEX idx_status (status),
        INDEX idx_sync_date (sync_date),
        INDEX idx_created_at (created_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单表'";
    
    $pdo->exec($sql);
    echo "orders表创建成功\n";
    
    // 验证表结构
    $stmt = $pdo->query('DESCRIBE orders');
    $columns = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "\norders表结构:\n";
    foreach ($columns as $column) {
        echo $column['Field'] . ' - ' . $column['Type'] . ' - ' . $column['Null'] . ' - ' . $column['Key'] . ' - ' . $column['Default'] . ' - ' . $column['Extra'] . "\n";
    }
    
} catch (Exception $e) {
    echo "错误: " . $e->getMessage() . "\n";
} 